<template>
  <el-dialog
    v-model="dialogVisible"
    :title="type === 'Ammeter' ? '新建电表' : 
            type === 'IndicatorMeter' ? '新建指示器' : '新建表'"

    width="30%"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="别名">
        <el-input v-model="form.alias" placeholder="请输入别名" />
      </el-form-item>

      <!-- 非电表时显示这些字段 -->
      <template v-if="type !== 'Ammeter' && type !== 'IndicatorMeter'"> <!-- 指示器，电表 -->
        <el-form-item label="量程">
          <el-input v-model="form.range" placeholder="请输入量程" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateDebounced">确定</el-button>
        
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    type: String
  },
  data() {
    return {
      form: {
        alias: '',
        range: '',
        unit: ''
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(value) {
        this.$emit('update:visible', value)
      }
    }
  },
  methods: {
    debounce(func, delay) {
      let timeout;
      return (...args) => {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), delay);
      };
    },
    
    handleCreate() {
      if (!this.form.alias) {
        this.$message.error('请输入别名');
        return;
      }

      if (this.type !== 'Ammeter' && this.type !== 'IndicatorMeter') {
        if (!this.form.range || !this.form.unit) {
          this.$message.error('请填写完整信息');
          return;
        }
      }

      this.$emit('create', {
        ...this.form,
        type: this.type
      });
    },

    handleCreateDebounced() {
      this.debounce(() => {
        this.handleCreate();
      }, 300)(); // 300ms 的防抖延迟
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.form = {
          alias: '',
          range: '',
          unit: ''
        }
      }
    }
  }
}
</script>


// /data
//    /data?monitorId=monitorId